<template>
  <div class="background">
    <div class="container">
      <div class="qu-wrap">
        <el-row style="margin-bottom: 10px">
          <el-col :span="4">
            <el-page-header @back="goBackDialogVisible = true"></el-page-header>
          </el-col>
          <el-col :span="16" style="display: inline-block;text-align: center">
            <input v-model="surveyTitle" class="surveyInfo" type="text" disabled style="font-size: 28px;font-weight: bold">
            </input>
          </el-col>
          <el-col :span="4"></el-col>
        </el-row>
        <el-row style="padding-top: 20px">
          <el-col :span="24" style="text-align: center">
            <input v-model="surveyIntroduction" class="surveyInfo" type="text" disabled style="color: #595959;text-decoration: #666666"></input>
          </el-col>
        </el-row>
        <el-row style="">
          <el-col :span="24" style="text-align: right; padding-bottom: 5px">
            <el-dropdown @command="handleImport">
              <el-button plain type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="0">从题库导入</el-dropdown-item>
                <el-dropdown-item command="1">导入历史问卷</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>

        <div class="qu-content">
          <section class="qu-item"
                   v-for="(item, index) in questions"
                   :class="{nowEditing: curIndex === index && topicEditing, optEditing: curIndex === index}">
            <h3 @click="curIndex = index; curOptIndex=''; topicEditing = true">
              <span class="qu-num" >{{`Q${index + 1}`}}</span>
              <span class="qu-topic" v-if="item.type === 0">{{`[单选] ${item.content}`}}</span>
              <span class="qu-topic" v-if="item.type === 1">{{`[文本] ${item.content}`}}</span>
              <span class="qu-topic" v-if="item.type === 2">{{`[多选] ${item.content}`}}</span>
              <input type="text"

                     v-model="content"
                     @focus="_content = content"
                     @blur="curIndex=''; content=''"
                     @keyup.esc="cancelTopicEdit()"
                     @keyup.enter="doneTopicEdit(index)">
              <span v-if="item.must==1"> *</span>
            </h3>
            <template v-if="item.type === 1">
              <textarea rows="8" cols="50" placeholder="请在此输入你的回答" disabled></textarea>
              <label id="require-check">
                <el-checkbox v-if="item.must==0" v-model="item.must" true-label="1" false-label="0">此题是否必填</el-checkbox>
                <el-checkbox v-if="item.must==1" checked="true" v-model="item.must" true-label="1" false-label="0">此题是否必填</el-checkbox>
              </label>
            </template>
            <ul v-else class="options-list" >
              <li v-for="(option, optIndex) in item.optionContent"
                  :class="{optionEditing: curOptIndex === optIndex}">
                <span v-if="item.type===0"><el-radio value="0"></el-radio></span>
                <span v-if="item.type===2"><el-checkbox value="0"></el-checkbox></span>
                <span class="optionText"
                      @click="curIndex=index; curOptIndex=optIndex; topicEditing = false">{{ option }}</span>
                <input type="text"
                       v-model="optionText"
                       @focus="_optionText = optionText"
                       @blur="curIndex=''; optionText=''"
                       @keyup.esc="cancelOptionEdit()"
                       @keyup.enter="doneOptionEdit(index, optIndex)">
                <ul class="opt-ctrl">
                  <li v-if="optIndex !== 0"
                      @click="moveUp(optIndex, item.optionContent)">上移</li>
                  <li v-if="optIndex !== item.optionContent.length - 1"
                      @click="moveDown(optIndex, item.optionContent)">下移</li>
                  <li v-else @click="addOption(item.optionContent)">添加</li>
                  <li @click="delOption(optIndex, item.optionContent)">删除</li>
                </ul>
              </li>
            </ul>
            <ul class="operat-list">
              <li v-if="index !== 0"
                  @click="questionMoveUp(index)">上移</li>
              <li v-if="index !== questions.length - 1"
                  @click="questionMoveDown(index)">下移</li>
              <li @click="reuse(index)">复用</li>
              <li @click="delQuestion(index)">删除</li>
            </ul>
            <div></div>
          </section>
          <div class="add-box">
            <p class="qu-type" :class="{expand: isAdding}">
              <span @click="addType('0')">单选题</span>
              <span @click="addType('2')">多选题</span>
              <span @click="addType('1')">文本题</span>
            </p>

            <p class="add-btn" @click="isAdding = !isAdding;">
              <span>+ 添加问题</span>
            </p>
          </div>
          <el-row v-if="this.questions.length<1" style="height: 283px">
            <el-col :span="24"></el-col>
          </el-row>
          <el-row v-if="this.questions.length===1" style="height: 200px">
            <el-col :span="24"></el-col>
          </el-row>
          <el-row v-if="this.questions.length===2" style="height: 100px">
            <el-col :span="24"></el-col>
          </el-row>
        </div>

        <div style="padding-top: 20px">
          <el-row :span="24" align="middle" justify="space-between" type="flex">
            <el-col :span="24" style="text-align: right;">
              <el-button v-if="editTag===false" size="medium" type="primary" @click="confirmSurveyCreate()">创建问卷</el-button>
              <el-button v-if="editTag===true" size="medium" type="primary" @click="confirmSurveyEdit()">确认修改</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <div>
        <el-dialog title="提示" :visible.sync="goBackDialogVisible" width="30%">
          <span>将不会保存您的设计，确定返回？</span>
          <span slot="footer" class="dialog-footer">
        <el-button @click="goBackDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="goBack">确 定</el-button>
        </span>
        </el-dialog>
      </div>
      <div class="importFromQuestionBank">
        <el-dialog title="从题库导入" :visible.sync="questionBankDialogVisible" :close-on-click-modal="false" @close="handleQuestionDialogClose()">
          <el-row :span="24" style="padding-bottom: 10px">
            <el-col :span="8" style="text-align: left">
              <el-input v-model="keyword" placeholder="请输入要查询的题目名" clearable></el-input>
            </el-col>
            <el-col :span="12" style="text-align: left; padding-left: 10px">
              <el-button type="primary" size="medium" icon="el-icon-search" @click="queryQuestionsByKey()">查询</el-button>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button type="primary" size="medium" icon="el-icon-plus" plain @click="importFromQuestionBank()">导入</el-button>
            </el-col>
          </el-row>
          <el-table :data="questionBankData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                    :row-key="getRowKeys"
                    @selection-change="handleQuestionSelectChange"
                    ref="questionBankTable"
                    border stripe>
            <el-table-column type="selection" align="center" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" type="index" width="60" align="center">
              <template v-slot="scope">
                <span>{{(currentPage-1)*pageSize+1+scope.$index}}</span>
              </template>
            </el-table-column>
            <el-table-column property="content" label="题干信息" align="center" width="500"></el-table-column>
            <el-table-column property="type" label="问题类型" align="center"></el-table-column>
            <el-table-column property="optionContent" label="选项内容" v-if="false"></el-table-column>
          </el-table>
          <div class="pagination" style="padding-top: 5px; text-align: right">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </el-dialog>
      </div>
      <div class="importFromHistorySurvey">
        <el-dialog title="导入历史问卷" :visible.sync="historySurveyDialogVisible" :close-on-click-modal="false" @close="handleSurveyDialogClose()">
          <el-row :span="24" style="padding-bottom: 5px; text-align: right">
            <el-col :span="8" style="text-align: left">
              <el-input v-model="keyword" placeholder="请输入要查询的问卷名" clearable></el-input>
            </el-col>
            <el-col :span="12" style="text-align: left; padding-left: 10px">
              <el-button type="primary" size="medium" icon="el-icon-search" @click="querySurveysByKey()">查询</el-button>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button type="primary" size="medium" icon="el-icon-plus" plain @click="importFromHistorySurvey()">导入</el-button>
            </el-col>
          </el-row>
          <el-table :data="historySurveyData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                    ref="historySurveyTable"
                    :row-key="getRowKeys"
                    @select="handleSurveySelect"
                    border stripe>
            <el-table-column type="selection" align="center" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" type="index" width="60" align="center">
              <template v-slot="scope">
                <span>{{(currentPage-1)*pageSize+1+scope.$index}}</span>
              </template>
            </el-table-column>
            <el-table-column property="title" label="问卷名称" align="center"></el-table-column>
            <el-table-column property="introduction" label="问卷介绍" align="center" width="450"></el-table-column>
          </el-table>
          <div class="pagination" style="padding-top: 5px; text-align: right">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {createSurvey, editSurvey, getSurveyDetail, querySurveyList} from '../../../api/survey'
import {queryQuestionList} from "../../../api/user/user-question";

export default {
	name: 'Edit',
	data() {
		return {
      editTag: false,
      surveyId: '',
      surveyTitle: '',
      surveyIntroduction: '',
      maxAnswers: null,
      startTime: '',
      endTime: '',
      questionTemplate:{
        0: {
          "type": 0,
          "content": "请输入题目",
          "optionContent": ["选项1","选项2","选项3","选项4"]
        },
        2: {
          "type": 2,
          "content": "请输入题目",
          "optionContent": ["选项1","选项2","选项3","选项4"]
        },
        1: {
          "type": 1,
          "content": "请输入题目",
          "must": 0
        }
      },

			index: '',
			quData: {},
			questions: [],

			title: '',
			_title: '',
			content: '',
			_content: '',
			optionText: '',
			_optionText: '',
			curIndex: '',
			curOptIndex: '',
			promptText: '',
			iterator: {},
			isAdding: false,
			titleEditing: false,
			topicEditing: false,
			isShowPrompt: false,
			isShowDatepicker: false,

      goBackDialogVisible: false,

      questionBankDialogVisible: false,
      questionBankData: [],
      // selectedQuestionIds: [],
      selectedQuestions: [],

      historySurveyDialogVisible: false,
      historySurveyData: [],
      selectedSurveyId: '',
      selectedSurvey: '',

      pageSize: 5,
      currentPage: 1,
      total: 0,

      keyword: '',
    }
	},

	created() {
    let survey = JSON.parse(window.sessionStorage.getItem("survey"))
    this.surveyTitle = survey.title
    this.surveyIntroduction = survey.introduction
    this.maxAnswers = survey.maxAnswers
    this.startTime = survey.startToEnd[0]
    this.endTime = survey.startToEnd[1]
    if(window.sessionStorage.getItem("surveyInfo")!==null){
      this.editTag = true
      let survey = JSON.parse(window.sessionStorage.getItem("surveyInfo"))
      this.surveyTitle = survey.title
      this.surveyId = survey.id
      // this.surveyIntroduction = survey.introduction
      this.questions = JSON.parse(window.sessionStorage.getItem("questionArray"))
      window.sessionStorage.removeItem("surveyInfo")
      window.sessionStorage.removeItem("questionArray")
    }
    // console.log(this.startTime)
    // console.log(this.endTime)
	},


	methods: {
    goBack () {
      this.$router.push({path: "/user/survey"})//TODO:待更改
    },
    confirmSurveyCreate () {
      // console.log(this.questions)
      // return
      if(this.questions.length===0){
        this.$message.warning("问卷还没有任何问题")
        return
      }
      // console.log("questions[]:")
      // console.log(this.questions)
      // console.log(JSON.stringify(this.questions))
      //TODO:session获取id,目前id写死
      let userId = JSON.parse(window.sessionStorage.getItem("data")).id


      createSurvey(
        userId,
        this.surveyTitle,
        this.surveyIntroduction,
        this.maxAnswers,
        this.startTime,
        this.endTime,
        this.questions).then((response=>{
        // console.log(response)
        const httpResult = response.data
        if(httpResult.code === 200){
          this.$message.success("创建成功")
          // console.log(httpResult.data)
          this.goBack()
        }else {
          this.$message.error(httpResult.message)
        }
      }))

    },
    confirmSurveyEdit() {
      if(this.questions.length===0){
        this.$message.warning("问卷还没有任何问题")
        return
      }
      //TODO:session获取id,目前id写死
      let userId = JSON.parse(window.sessionStorage.getItem("data")).id
      editSurvey(
        userId,
        this.surveyId,
        this.surveyTitle,
        this.surveyIntroduction,
        this.maxAnswers,
        this.startTime,
        this.endTime,
        this.questions
      ).then((response)=>{
        // console.log(response)
        const httpResult = response.data
        if(httpResult.code === 200){
          this.$message.success("修改成功")
          this.goBack()
        }else {
          this.$message.error(httpResult.message)
        }
      })
    },

    handleImport(command){
      // 从题库导入
      if(command == '0'){
        // 清空复选框内容
        this.$nextTick(() => {
          this.$refs.questionBankTable.clearSelection()
        });

        queryQuestionList('').then((response)=>{
          const httpResult = response.data;
          this.questionBankData = httpResult.data;
          this.total = httpResult.data.length;
          this.currentPage = 1;
          this.pageSize = 5;
          this.questionBankDialogVisible = true;
        })
      }

      // 导入历史问卷
      if(command == '1'){
        // 清空复选框内容
        this.$nextTick(() => {
          this.$refs.historySurveyTable.clearSelection()
        });

        let userId = JSON.parse(window.sessionStorage.getItem("data")).id
        querySurveyList(userId, '').then((response)=>{
          const httpResult = response.data;
          this.historySurveyData = httpResult.data;
          this.total = httpResult.data.length;
          this.currentPage = 1;
          this.pageSize = 5;
          this.historySurveyDialogVisible = true;
        })
      }
    },

    importFromQuestionBank(){
      // 问题数目判断，不能超过10题
      if(this.selectedQuestions.length + this.questions.length > 10){
        this.$message.error('每份问卷最多10个问题，导入题目失败!')
        this.handleQuestionDialogClose()
        // this.questionBankDialogVisible = false
        return
      }else if(this.selectedQuestions.length === 0){
        this.$message.warning('请选择要导入的问题!')
        return
      }

      for(let i = 0; i < this.selectedQuestions.length; i++){
        this.selectedQuestions[i].optionContent = JSON.parse(this.selectedQuestions[i].optionContent)
        this.questions.push(this.selectedQuestions[i])
      }
      this.$message.success('导入题目成功')
      this.handleQuestionDialogClose()
      // this.questionBankDialogVisible = false
    },

    importFromHistorySurvey(){
      if(this.selectedSurveyId == ''){
        this.$message.warning('请选择要导入的历史问卷!')
        return
      }

      getSurveyDetail(this.selectedSurveyId).then((response)=>{
        const httpResult = response.data;
        if(httpResult.code == '200'){
          let questionArray = httpResult.data.questionArray
          // 问题数目判断，不能超过10题
          if(questionArray.length + this.questions.length > 10){
            this.$message.error('每份问卷最多10个问题，导入问卷失败!')
            // this.historySurveyDialogVisible = false
            this.handleSurveyDialogClose()
            return
          }

          for(let i = 0; i < questionArray.length; i++){
            this.questions.push(questionArray[i])
          }
          this.$message.success('导入问卷成功')
          this.handleSurveyDialogClose()
          // this.historySurveyDialogVisible = false;
        }else{
          this.$message.error('导入问卷出错')
          this.handleSurveyDialogClose()
        }
      })
    },

    queryQuestionsByKey(){
      queryQuestionList(this.keyword).then((response)=>{
        const httpResult = response.data
        this.questionBankData = httpResult.data
        this.total = httpResult.data.length;
        this.currentPage = 1;
        this.pageSize = 5;
      })
    },

    querySurveysByKey(){
      let userId = JSON.parse(window.sessionStorage.getItem("data")).id
      querySurveyList(userId, this.keyword).then((response)=>{
        const httpResult = response.data;
        this.historySurveyData = httpResult.data;
        this.total = httpResult.data.length;
        this.currentPage = 1;
        this.pageSize = 5;
        this.historySurveyDialogVisible = true;
      })
    },

    handleQuestionDialogClose(){
      this.selectedQuestions = []
      this.keyword = ''
      this.questionBankDialogVisible = false
    },

    handleSurveyDialogClose(){
      this.selectedSurveyId = ''
      this.keyword = ''
      this.historySurveyDialogVisible = false
    },

    handleQuestionSelectChange(val){
      this.selectedQuestions = val
    },

    handleSurveySelect(selection, row){
      // 实现复选框单选
      this.$refs.historySurveyTable.clearSelection()
      if(selection.length == 0) return
      this.$refs.historySurveyTable.toggleRowSelection(row, true);

      // console.log(row.id)
      this.selectedSurveyId = row.id
      // console.log(this.selectedSurveyId)
    },

    getRowKeys(row) {
      return row.id;
    },

    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
    },

		cancelTopicEdit() {
			this.topicEditing = false;
			this.topic = this._topic;
		},

		cancelOptionEdit() {
			this.curOptIndex = '';
			this.optionText = this._optionText;
		},

		doneTopicEdit(index) {
      // console.log("index:")
      // console.log(index)
			this.topicEditing = false;
			this.questions[index].content = this.content;
		},

		doneOptionEdit(index, optIndex) {
			this.curOptIndex = '';
			this.questions[index].optionContent[optIndex] = this.optionText;
		},

		switchItem(index, array) {
			this.optIndex = '';
			this.curIndex = '';

			let arr = array.splice(index, 2);
			array.splice(index , 0, ...arr.reverse());
		},

    questionMoveUp(index) {
      this.switchItem(index - 1, this.questions);
    },

		moveUp(index,array) {
			this.switchItem(index - 1, array);
		},

		questionMoveDown(index) {
			this.switchItem(index, this.questions);
		},

    moveDown(index,array) {
      this.switchItem(index, array);
    },

		errorPrompt(text) {
			this.iterator = null;
			this.showPrompt(text);
		},

		reuse(index) {
			if (this.questions.length === 10) {
				this.errorPrompt(`每份问卷至多10个问题！`);
				return;
			}
			let oldQuestion = this.questions[index];
			let newQuestion = JSON.parse(JSON.stringify(oldQuestion));
			this.questions.splice(index, 0, newQuestion);
		},

		delQuestion(index) {
			// if (this.questions.length <= 1) {
			// 	this.errorPrompt(`每份问卷至少一个问题！`);
			// 	return;
			// }
			this.questions.splice(index, 1);
		},

		delOption(index, options) {
			if (options.length <= 2) {
				this.errorPrompt(`每个问题至少两个选项`);
				return;
			}
			options.splice(index, 1)
		},

		addOption(options) {
			options.push(`请编辑选项内容`)
		},

		showPrompt(text) {
			this.promptText = text;
			this.isShowPrompt = true;
		},

		addType(type) {
			if (this.questions.length === 10) {
				this.errorPrompt(`每份问卷至多10个问题！`);
				return;
			}
      let template = this.questionTemplate[type];
      let newQues = JSON.parse(JSON.stringify(template));
      this.questions.push(newQues);
			// this.questions.push(this.questionTemplate[type]);
      // this.questions.push(JSON.parse(JSON.stringify(this.questions[type])));

		},
	},
}

</script>

<style>
@import "../../../style/questionnaireStyle/style.css";
.surveyInfo{
  width: 500px;
  height: 30px;
  color: #000000;
  background-color: #fff;
  border: none;
  border-bottom: 1px;
  outline: none;
  text-align: center;
  font-size: 20px;
}
.background{
  background-image: url("../../../assets/answerbackground.png");
  background-size: 100% 100%;
  margin: 0;
  width: 100vw;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 0px;
}
</style>
